using AiQiuQuan.Sport.Model.Models;
using AiQiuQuan.Sport.WebApi.Entities;
using AiQiuQuan.Sport.WebApi.Repositories;
using MapsterMapper;
using Microsoft.EntityFrameworkCore;

namespace AiQiuQuan.Sport.WebApi.Services.Impl
{
    /// <summary>
    /// 支付单管理
    /// </summary>
    public class PayOrderService : IPayOrderService
    {
        private readonly IMapper _mapper;
        private readonly IPayOrderRepository _payOrderRepository;

        /// <summary>
        /// ctor
        /// </summary>
        public PayOrderService(
            IMapper mapper,
            IPayOrderRepository payOrderRepository)
        {
            _mapper = mapper;
            _payOrderRepository = payOrderRepository;
        }

        /// <summary>
        /// 支付成功查询
        /// </summary>
        public async Task<PaySuccessDto> GetPayOrderInfoAsync(Guid orderId)
        {
            var payOrder = await _payOrderRepository.FirstOrDefaultAsync(m => m.BusinessId == orderId);
            if (payOrder == null)
            {
                return null;
            }

            return _mapper.Map<PaySuccessDto>(payOrder);
        }

        /// <summary>
        /// 支付单分页查询
        /// </summary>
        public async Task<PageResult<PayOrderDto>> PageListAsync(PayOrderPageRequestDto request)
        {
            var query = _payOrderRepository.AsNoTracking();
            if (!string.IsNullOrWhiteSpace(request.OrderNo))
            {
                query = query.Where(m => m.OrderNo.Contains(request.OrderNo));
            }

            if (request.BusinessType.HasValue)
            {
                query = query.Where(m => m.BusinessType == request.BusinessType.Value);
            }

            if (request.PayType.HasValue)
            {
                query = query.Where(m => m.PayType == request.PayType.Value);
            }

            if (!string.IsNullOrWhiteSpace(request.ProductName))
            {
                query = query.Where(m => m.ProductName.Contains(request.ProductName));
            }

            if (request.PayState.HasValue)
            {
                query = query.Where(m => m.PayState == request.PayState.Value);
            }

            if (request.CreateTime.HasValue)
            {
                query = query.Where(m => m.CreateTime >= request.CreateTime.Value);
            }

            var result = await query.OrderByDescending(m => m.CreateTime).PageListAsync<PayOrder, PayOrderDto>(request, _mapper);
            return result;
        }
    }
}